package com.woniu.adminservice.controller;

import com.github.pagehelper.PageInfo;
import com.woniu.adminservice.commeon.CommonResult;
import com.woniu.adminservice.dto.AdminDTO;
import com.woniu.adminservice.entity.Account;
import com.woniu.adminservice.service.AccountService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/account")
public class AccountController {
    @Resource
    private AccountService accountService;

    @GetMapping("selectOne")
    public Account selectOne(Integer id) {
        return accountService.queryById(id);
    }

    /**
     * 用户列表
     * @return
     */
    @GetMapping("/list")
    public CommonResult getMenus(@RequestParam(value = "page",defaultValue = "1",required = false)Integer currentPage,
                                 @RequestParam(value = "limit",defaultValue = "5",required = false)Integer pageSize){
        PageInfo info = null;
        try {
            List<Account> list =accountService.findAllByPage(currentPage,pageSize);
            info =new PageInfo(list);
            return CommonResult.success(info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonResult.failed();
    }

    /**
     * 登录认证
     * @return
     */
    @RequestMapping("/subLogin")
    @ResponseBody
    public CommonResult subLogin(Account account){
        if(StringUtils.isEmpty(account.getAccount())){
            return CommonResult.failed("用户名不能为空");
        }
        if(StringUtils.isEmpty(account.getPassword())){
            return CommonResult.failed("密码不能为空");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(account.getAccount(),account.getPassword());
        try {
            //提交到自定义域中认证
            subject.login(token);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return CommonResult.failed("账号不存在");
        }catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return CommonResult.failed("账号或密码错误");
        }catch (AuthenticationException e) {
            e.printStackTrace();
            return CommonResult.failed("认证失败");
        }
        return CommonResult.success("登录成功");

    }


}